﻿using System;
using System.Web.Mvc;
using DotNetOpenAuth.Messaging;
using DotNetOpenAuth.OpenId.RelyingParty;
using StructureMap;
using DotNetOpenAuthStatus = DotNetOpenAuth.OpenId.RelyingParty.AuthenticationStatus;

namespace Yala.Client.Web.MVC.Authentication.DotNetOpenAuth
{
    public class DotNetOpenAuthOpenIdRelyingParty : IDotNetOpenAuthOpenIdRelyingParty
    {
        private OpenIdRelyingParty _openIdRelyingParty;

        public DotNetOpenAuthOpenIdRelyingParty(OpenIdRelyingParty openIdRelyingParty)
        {
            _openIdRelyingParty = openIdRelyingParty;
        }

        public IAuthenticationResponse GetResponse()
        {
            var response = _openIdRelyingParty.GetResponse();
            var result = ObjectFactory.GetInstance<IAuthenticationResponse>();

            if (response != null)
            {
                switch (response.Status)
                {
                    case DotNetOpenAuthStatus.Authenticated:
                        result.Status = AuthenticationStatus.Authenticated;
                        result.ClaimIdentifier = response.ClaimedIdentifier;
                        result.FriendlyIdentifierForDisplay = response.FriendlyIdentifierForDisplay;
                        return result;
                    case DotNetOpenAuthStatus.Canceled:
                        result.Status = AuthenticationStatus.Canceled;
                        return result;
                    case DotNetOpenAuthStatus.ExtensionsOnly:
                        result.Status = AuthenticationStatus.ExtentionsOnly;
                        return result;
                    case DotNetOpenAuthStatus.Failed:
                        result.Status = AuthenticationStatus.Failed;
                        result.Exception = response.Exception;
                        return result;
                    case DotNetOpenAuthStatus.SetupRequired:
                        result.Status = AuthenticationStatus.SetupRequired;
                        return result;
                }
            }
            else
            {
                result.IsNullResponse = true;
                return result;
            }

            return result;
        }

        public ActionResult CreateRequest(string openIdProvider)
        {
            if (_openIdRelyingParty != null)
                return _openIdRelyingParty.CreateRequest(openIdProvider).RedirectingResponse.AsActionResult();
            else
            {
                throw new NotImplementedException();
            }
        }
    }
}